<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="renderer" content="webkit">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>申报者管理</title>
@include('common-css')
<style>
.input_box {
    width: 100%;
    height: 40px;
    margin-top: 15px;
    margin-bottom: 15px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
}

.input_label {
    width: 120px;
    box-sizing: border-box;
}

.application-list {
    position: relative;
    margin-top: 20px;
}

.phase-tag {
    color: #1890ff;
    border: 1px solid #91d5ff;
    border-radius: 3px;
    background: #e6f7ff;
    font-size: 12px;
    padding: 2px 3px;
}

.ant-table-tbody > tr > td, .ant-table-thead > tr > th {
    vertical-align: middle;
    line-height: 25px;
}

.action-table .ant-select {
    width: 120px;
}

.action-table .search-td {
    display: flex;
    justify-content: flex-start;
}

.action-table .ant-input {
    width: 178px;
}

.action-table .search-td .ant-btn {
    margin-left: 16px;
}

.my-pagination {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
}

.common_box {
    position: relative;
}

.search-box {
    position: absolute;
    right: 30px;
    top: 58px;
}

.search-box .ant-input {
    width: 300px;
}

.confirm-save-a {
    color: #52c41a;
}

.confirm-save-a:hover {
    color: #52c41a;
}

.cancel-save-a {
    color: #faad14;
}

.cancel-save-a:hover {
    color: #faad14;
}

.delete-btn-a {
    color: #f5222d
}

.login_input_container {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    padding: 0 20px 20px;
}

.input_box {
    width: 100%;
    height: 40px;
    margin-top: 15px;
    margin-bottom: 15px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
}

.input_label {
    width: 120px;
    box-sizing: border-box;
}

.add-user-div {
    margin-bottom: 16px;
}

.ant-input-suffix {
    cursor: pointer;
}
</style>
</head>
<body>
<div id="app">

</div>
</body>
</html>

<script id="appTemplate" type="x-template">
<a-locale-provider :locale="antdLocale">
    <div class="container">

        @include('admin.header-tpl')

        <main>
            <div class="common_container">

                @include('admin.aside-tpl')

                <div class="common_content">
                    <div class="common_box">
                        <div class="add-user-div">
                            <a-button type="primary" @click="addUserModelVisible = true">添加申报者</a-button>
                        </div>
                        <table class="action-table">
                            <tr>
                                <td width="100">用户类型</td>
                                <td>
                                    <a-radio-group :value="filters.entityTypeFilter"
                                                   @change="handleEntityTypeFilterChange">
                                        <a-radio-button value="">不限</a-radio-button>
                                        <a-radio-button v-for="item in allEntityTypes"
                                                        :value="item.value"
                                                        :key="item.value">@{{ item.label }}
                                        </a-radio-button>
                                    </a-radio-group>
                                </td>
                            </tr>
                            <tr v-if="false">
                                <td width="100">排序筛选</td>
                                <td>
                                    <a-select v-model="filters.sortBy" @change="handleSortByChange">
                                        <a-select-option value="">默认排序</a-select-option>
                                        <a-select-option value="id|asc">ID ↑</a-select-option>
                                        <a-select-option value="id|desc">ID ↓</a-select-option>
                                        <a-select-option value="created_at|asc">创建时间 ↑</a-select-option>
                                        <a-select-option value="created_at|desc">创建时间 ↓</a-select-option>
                                    </a-select>
                                </td>
                            </tr>
                            <tr v-if="false">
                                <td width="100">搜索筛选</td>
                                <td class="search-td">
                                    <a-input v-model="filters.keyword" placeholder="按回车键搜索"
                                             @pressEnter="handleKeywordFilterChange">
                                    </a-input>
                                    <a-button @click="resetSearch">重置</a-button>
                                </td>
                            </tr>
                        </table>
                        <div class="search-box">
                            <a-input v-model="filters.keyword" placeholder="按回车键搜索"
                                     @pressEnter="handleKeywordFilterChange">
                                <a-icon v-show="filters.keyword != ''" slot="suffix" type="close"
                                        style="color:#bfbfbf;font-size:13px"
                                        @click="resetSearch"/>
                            </a-input>
                        </div>
                        <a-table class="application-list"
                                 rowKey="id"
                                 :columns="manageUserListColumns"
                                 :dataSource="pageData"
                                 :pagination="false"
                        >
                            <template
                                    v-for="col in ['username', 'entity_type', 'email', 'name', 'org_contact', 'tel']"
                                    :slot="col"
                                    slot-scope="text, record, index">
                                <div :key="col">
                                    <template v-if="record.editable">
                                        <a-textarea v-if="col != 'entity_type'"
                                                    autosize
                                                    style="margin: -5px 0; width:100%;"
                                                    :value="text"
                                                    @change="e => handleChange(e.target.value,record.id, col)"
                                        />
                                        <a-select v-else v-model="record.entity_type"
                                                  @change="e => handleChange(e, record.id, col)">
                                            <a-select-option value="personal">个人</a-select-option>
                                            <a-select-option value="org">单位</a-select-option>
                                        </a-select>
                                    </template>
                                    <template v-else>
                                        <span v-if="col == 'entity_type'">@{{text | entityTypeFilter}}</span>
                                        <span v-else>@{{text == null || text == '' ? '-' : text }}</span>
                                    </template>
                                </div>
                            </template>
                            <span slot="created_at" slot-scope="text, record">
                                    @{{ record.created_at | shortDateTime }}
                                </span>
                            <template slot="operations" slot-scope="text, record, index">
                                <div class='editable-row-operations'>
                                    <span v-if="record.editable">
                                        <a @click="save(record.id)">保存</a>
                                        <a @click="cancel(record.id)">取消</a>
                                    </span>
                                    <span v-else>
                                        <a @click="() => edit(record.id)">编辑</a>
                                        <a @click="showChangeUserModal(record)" style="margin-left: 12px;">修改密码</a>
                                        <a-popconfirm title="确认删除该用户？"
                                                      @confirm="handleDeleteUser(record)"
                                                      okText="是"
                                                      cancelText="否">
                                            <a class="delete-btn-a" style="margin-left: 12px;">删除</a>
                                        </a-popconfirm>
                                    </span>
                                </div>
                            </template>
                        </a-table>
                        <div class="my-pagination">
                            <a-pagination :pageSize="pageSize"
                                          :current="currentPage" :total="totalCount"
                                          :showTotal="total => `共 ${total} 条`"
                                          @change="handlePageChange"/>
                        </div>
                    </div>
                </div>
            </div>
        </main>

        <a-modal
                title="营业执照"
                v-model="flags.showOrgPhotoDialogVisible"
                @ok="flags.showOrgPhotoDialogVisible = false"
        >
            <p>
                <img style="display: block; width: 100%;" :src="currentBizLicPhotoUrl"/>
            </p>
        </a-modal>
        <a-modal :width="500" v-model="addUserModelVisible" title="添加申报者"
                 @ok="handleAddApplicant" @cancel="addUserModelVisible = false">
            <div class="login_input_container">

                <div class="input_box">
                    <div class="input_label">用户类型</div>
                    <div class="input_box">
                        <a-radio-group @change="" v-model="newUserInfo.entity_type">
                            <a-radio value="personal">个人</a-radio>
                            <a-radio value="org">单位</a-radio>
                        </a-radio-group>
                    </div>
                </div>

                <div class="input_box">
                    <div class="input_label">用户名</div>
                    <div class="input_box">
                        <a-input placeholder="3-16位，可使用字母、数字、下划线" size="large" v-model="newUserInfo.username"
                                 ref="usernameInput" autoFocus>
                        </a-input>
                    </div>
                </div>

                <div class="input_box">
                    <div class="input_label">邮箱</div>
                    <div class="input_box">
                        <a-input placeholder="输入登录邮箱" size="large" v-model="newUserInfo.email" ref="emailInput">
                        </a-input>
                    </div>
                </div>
                <div class="input_box">
                    <div class="input_label">密码</div>
                    <div class="input_box">
                        <a-input placeholder="8-16位" maxlength="16" size="large"
                                 :type="newUserInfo.showPassword ? 'text' : 'password'"
                                 v-model="newUserInfo.password"
                                 autocomplete="new-password">
                            <a-icon slot="suffix" :type="newUserInfo.showPassword ? 'eye-invisible' : 'eye'"
                                    @click="newUserInfo.showPassword = !newUserInfo.showPassword"/>
                        </a-input>
                    </div>
                </div>

                <template v-if="newUserInfo.entity_type == 'personal'">

                    <div class="input_box">
                        <div class="input_label">姓名</div>
                        <div class="input_box">
                            <a-input placeholder="输入真实姓名" size="large" v-model="newUserInfo.name">
                            </a-input>
                        </div>
                    </div>
                    <div class="input_box">
                        <div class="input_label">联系电话</div>
                        <div class="input_box">
                            <a-input placeholder="输入常用手机号" maxlength="11" size="large" v-model="newUserInfo.tel">
                            </a-input>
                        </div>
                    </div>
                    <div class="input_box">
                        <div class="input_label">工作单位</div>
                        <div class="input_box">
                            <a-input placeholder="输入单位名称" size="large" v-model="newUserInfo.work_org_name">
                            </a-input>
                        </div>
                    </div>

                </template>

                <template v-else>

                    <div class="input_box">
                        <div class="input_label">单位名称</div>
                        <div class="input_box">
                            <a-input placeholder="输入单位完整名称" size="large" v-model="newUserInfo.name">
                            </a-input>
                        </div>
                    </div>
                    <div class="input_box">
                        <div class="input_label">营业执照<br>(可选)</div>
                        <div class="input_box">
                            <template v-if="newUserInfo.org_biz_lic_photo">
                                <span style="color:green;">上传成功，请继续完成注册</span>
                            </template>
                            <template v-else>
                                <div>
                                    <a-upload name="file" accept=".jpg,.jpeg,.png" :showUploadList="false"
                                              action="/api/common/upload"
                                              :beforeUpload="handleOrgBusinessLicensePhotoBeforeUpload"
                                              @change="handleOrgBusinessLicensePhotoUploadChange($event)">
                                        <a-button>上传图片</a-button>
                                    </a-upload>
                                </div>
                                <p style="margin-left: 10px; font-size: 14px; color:#666; line-height: 20px;">
                                    加盖公章的扫描件，JPG 格式，供管理员审核</p>
                            </template>
                        </div>
                    </div>
                    <div class="input_box">
                        <div class="input_label">联系人</div>
                        <div class="input_box">
                            <a-input placeholder="输入联系人姓名" size="large" v-model="newUserInfo.org_contact">
                            </a-input>
                        </div>
                    </div>
                    <div class="input_box">
                        <div class="input_label">联系电话</div>
                        <div class="input_box">
                            <a-input placeholder="输入联系电话" size="large" v-model="newUserInfo.tel">
                            </a-input>
                        </div>
                    </div>
                </template>
            </div>
        </a-modal>
        <a-modal v-model="adminChangePasswordDialogVisible" :width="400" title="修改密码"
                 @ok="adminHandleChangePasswordOk">
            <div class="input_box">
                <div class="input_label">新密码</div>
                <div class="input_box">
                    <a-input placeholder="8-16位" maxlength="16" size="large" type="password"
                             v-model="passwordInfo.password" autocomplete="new-password">
                    </a-input>
                </div>
            </div>
            <div class="input_box">
                <div class="input_label">确认新密码</div>
                <div class="input_box">
                    <a-input placeholder="确认新密码" maxlength="16" size="large" type="password"
                             v-model="passwordInfo.passwordConfirm" autocomplete="new-password">
                    </a-input>
                </div>
            </div>
        </a-modal>
    </div>
</a-locale-provider>
</script>

@include('common-js')

@include('admin.header-js')
@include('admin.aside-js')

<script>
var queryParams = parseUrl(location.href).params;

const manageUserListColumns = [
    {
        width: 80,
        title: '序号',
        dataIndex: 'num'
    }, {
        width: 100,
        title: '用户名',
        dataIndex: 'username',
        scopedSlots: {
            customRender: 'username'
        }
    }, {
        width: 80,
        title: '类型',
        dataIndex: 'entity_type',
        scopedSlots: {
            customRender: 'entity_type'
        }
    }, {
        width: 150,
        title: '邮箱',
        dataIndex: 'email',
        scopedSlots: {
            customRender: 'email'
        }
    }, {
        width: 130,
        title: '单位名称/姓名',
        dataIndex: 'name',
        scopedSlots: {
            customRender: 'name'
        }
    }, {
        width: 90,
        title: '联系人',
        dataIndex: 'org_contact',
        scopedSlots: {
            customRender: 'org_contact'
        }
    }, {
        width: 90,
        title: '联系电话',
        dataIndex: 'tel',
        scopedSlots: {
            customRender: 'tel'
        }
    }, {
        width: 120,
        title: '创建时间',
        dataIndex: 'created_at',
        scopedSlots: {
            customRender: 'created_at'
        }
    }, {
        width: 160,
        title: '操作',
        dataIndex: 'operations',
        scopedSlots: {
            customRender: 'operations'
        }
    }];

function processOrgUsersData(pageData, page) {
    var n = (page - 1) * 10 + 1;
    pageData.forEach(item => {
        item.num = n;
        n += 1
    });
    return pageData
}

Vue.prototype.$axios = axios;
var app = new Vue({
    el: '#app',
    template: '#appTemplate',
    data: {
        isSending: false,
        addUserModelVisible: false,
        newUserInfo: {
            entity_type: 'personal',
            username: '',
            email: '',
            password: '',
            check: '',
            name: '',
            org_biz_lic_photo: '',
            org_contact: '',
            tel: '',
            work_org_name: '',
            showPassword: false
        },
        flags: {
            showOrgPhotoDialogVisible: false,
        },
        currentBizLicPhotoUrl: '',
        manageUserListColumns: manageUserListColumns,
        cacheData: [],
        allEntityTypes: [
            {
                value: 'personal',
                label: '个人'
            },
            {
                value: 'org',
                label: '单位'
            }
        ],
        currentPage: 1,
        pageSize: 10,
        pageData: [],
        totalCount: 0,
        filters: {
            entityTypeFilter: '',
            sortBy: '',
            keyword: ''
        },
        adminChangePasswordDialogVisible: false,
        changePasswordUserId: '',
        asideSelectedKeys: [queryParams.aside_key],
        antdLocale: antd.locales.zh_CN,
        ...AdminHeader.data,
        ...AdminAside.data,
    },
    filters: {
        entityTypeFilter(value) {
            if (value === 'personal') {
                return '个人'
            } else {
                return '单位'
            }
        },
        shortDateTime(value) {
            if (value) {
                return moment(value).format('Y/M/D H:mm')
            }
            return value
        }
    },
    computed: {},
    beforeMount() {
        this.loadAsideDefaultOpenKeys()
    },
    mounted() {
        this.fetchData();
        this.reloadAsideData()
    },
    methods: {
        showChangeUserModal(user) {
            this.changePasswordUserId = user.id;
            this.adminChangePasswordDialogVisible = true
        },
        adminHandleChangePasswordOk() {
            let {password, passwordConfirm} = this.passwordInfo;
            if (!password) return this.$message.error("请填写密码");
            if (password.length < 8 || password.length > 16) return this.$message.error("密码长度应为8-16位");
            if (!passwordConfirm) return this.$message.error("请确认密码");
            if (password != passwordConfirm) return this.$message.error("两次填写密码不一致");
            let encryptedText = encrypt.encrypt(password);
            this.$message.loading('正在处理', 0);
            this.$axios.post("/api/auth/admin-change-password", {
                password: encryptedText,
                user_id: this.changePasswordUserId
            }).then(res => {
                this.$message.destroy();
                this.adminChangePasswordDialogVisible = false;
                console.log(res);
                if (res.data.ok) {
                    this.$message.success("密码修改成功")
                } else {
                    this.$message.error(res.data.message)
                }
            })
        },
        handleAddApplicant() {
            let {entity_type, username, email, password, check, name, org_biz_lic_photo, org_contact, tel, work_org_name} = this.newUserInfo;
            if (this.isSending) return;
            if (!username) return this.$message.error("请填写用户名");
            if (username.length < 3 || password.length > 16) return this.$message.error("用户名长度应为3-16位");
            if (!email) return this.$message.error("请填写邮箱");
            if (!email.includes("@")) return this.$message.error("邮箱格式不正确");
            if (!password) return this.$message.error("请填写密码");
            if (password.length < 8 || password.length > 16) return this.$message.error("密码长度应为8-16位");
            // if (!check) return this.$message.error("请确认密码")
            // if (password != check) return this.$message.error("两次填写密码不一致")

            if (entity_type == 'personal') {
                if (!name) return this.$message.error("请填写姓名");
                if (!tel) return this.$message.error("请填写联系电话");
                if (!work_org_name) return this.$message.error("请填写工作单位名称")
            } else {
                if (!name) return this.$message.error("请填写单位名称");
                // if (!org_biz_lic_photo) return this.$message.error("请上传营业执照")
                if (!org_contact) return this.$message.error("请填写联系人");
                if (!tel) return this.$message.error("请填写联系电话")
            }

            let encryptedText = encrypt.encrypt(password);
            this.isSending = true;
            this.$message.loading('正在提交...', 0);
            this.$axios.post("/api/auth/applicant-register", {
                entity_type,
                username,
                email,
                password: encryptedText,
                name,
                tel,
                work_org_name,
                org_biz_lic_photo,
                org_contact,
                admin_add: true
            }).then(res => {
                console.log(res);
                this.$message.destroy();
                this.isSending = false;
                if (res.data.ok) {
                    this.$message.success('添加成功');
                    history.go(0)
                } else {
                    this.$message.error(res.data.message)
                }
            })
        },
        handleOrgBusinessLicensePhotoBeforeUpload(file) {
            console.log('handleOrgBusinessLicensePhotoBeforeUpload', file);
            var filename = file.name.toLowerCase();
            if (filename.endsWith('.jpg') || filename.endsWith('.jpeg') || filename.endsWith('.png')) {
                antd.message.loading('正在上传...', 0);
                return true
            } else {
                antd.message.warn('不允许上传该文件格式');
                return false
            }
        },
        handleOrgBusinessLicensePhotoUploadChange(event) {
            console.log('handleOrgBusinessLicensePhotoUploadChange', event);
            if (event.file.status == 'done') {
                antd.message.destroy();
                if (event.file.response.ok) {
                    antd.message.success('上传成功，请继续完成注册');
                    this.newUserInfo.org_biz_lic_photo = event.file.response.url
                } else {
                    antd.message.warn('上传失败')
                }
            }
        },
        resetSearch() {
            // this.currentPage = 1
            this.filters.keyword = '';
            this.fetchData()
        },
        handleKeywordFilterChange(e) {
            console.log('keyword', e.target.value);
            // this.currentPage = 1
            this.filters.keyword = e.target.value;
            this.fetchData()
        },
        handleEntityTypeFilterChange(e) {
            // this.currentPage = 1
            this.filters.entityTypeFilter = e.target.value;
            this.fetchData()
        },
        fetchData(type = 'is_edit') {
            if (type === 'is_edit') {
                antd.message.loading('正在读取', 0)
            }
            axios.get('/api/auth/get-applicant-users-page-data', {
                params: {
                    page: this.currentPage,
                    pageSize: this.pageSize,
                    filters: this.filters
                }
            }).then(res => {
                console.log('res', res);
                antd.message.destroy();
                this.pageData = processOrgUsersData(res.data.data, res.data.current_page);
                this.cacheData = this.pageData.map(item => ({...item}));
                this.totalCount = res.data.total;
                this.currentPage = res.data.current_page
            })
        },
        handleSortByChange(value) {
            this.sortBy = value;
            this.fetchData()
        },
        handlePageChange(currentPage) {
            console.log('handlePageChange', currentPage);
            this.currentPage = currentPage;
            this.fetchData()
        },
        handleDeleteUser(user) {
            console.log('application', user);
            this.deletingUser = true;
            antd.message.loading('正在处理，请稍候', 0);
            axios.post('/api/auth/delete-user', {
                user_id: user.id
            }).then(res => {
                antd.message.destroy();
                console.log(res);
                var data = res.data;
                if (data.ok) {
                    antd.message.success('删除成功', 0);
                    this.fetchData('is_delete')
                } else {
                    antd.message.warn(data.message, 3)
                }
                this.deletingUser = false
            })
        },
        updateUserInfo(recordId, target, newData) {
            antd.message.loading('正在处理，请稍候', 0);
            axios.post('/api/auth/edit-user-by-id', {
                user_id: recordId,
                target
            }).then(res => {
                antd.message.destroy();
                console.log(res);
                var data = res.data;
                if (data.ok) {
                    delete target.editable;
                    this.pageData = newData;
                    this.cacheData = newData.map(item => ({...item}));
                    antd.message.success('修改成功')
                    // this.reloadData()
                } else {
                    antd.message.warn(data.message, 3)
                }
            })
        },
        handleChange(value, recordId, column) {
            console.log('rowData-change', value, recordId, column);
            const newData = [...this.pageData];
            const target = newData.filter(item => recordId === item.id)[0];
            if (target) {
                target[column] = value;
                this.pageData = newData
            }
        },
        edit(recordId) {
            console.log('edit-id', recordId);
            let newData = [...this.pageData];
            let target = newData.filter(item => recordId === item.id)[0];
            console.log('edit-target', target);
            if (target) {
                target.editable = true;
                this.pageData = newData
            }
        },
        save(recordId) {
            console.log('save-recordId', recordId);
            const newData = [...this.pageData];
            const target = newData.filter(item => recordId === item.id)[0];
            if (target) {
                if (!target.username) {
                    antd.message.warn('用户名不能为空');
                    return false
                }
                if (!target.email) {
                    antd.message.warn('邮箱不能为空');
                    return false
                }
                this.updateUserInfo(recordId, target, newData)
            }
        },
        cancel(recordId) {
            const newData = [...this.pageData];
            const target = newData.filter(item => recordId === item.id)[0];
            if (target) {
                Object.assign(target, this.cacheData.filter(item => recordId === item.id)[0]);
                delete target.editable;
                this.pageData = newData
            }
        },
        showBizLicPhoto(user) {
            this.currentBizLicPhotoUrl = user.org_biz_lic_photo;
            this.flags.showOrgPhotoDialogVisible = true
        },
        reloadData() {
            axios.post('/api/auth/get-certifying-org-user')
                .then(res => {
                    antd.message.destroy();
                    var orgUsers = res.data;
                    console.log(orgUsers);
                    processOrgUsersData(orgUsers);
                    this.orgUsers = orgUsers
                })
        },
        ...AdminHeader.methods,
        ...AdminAside.methods,
    }
})
</script>